package cn.virens.web.common;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.virens.database.common.BaseService;
import cn.virens.util.page.DataTableRequest;
import cn.virens.util.shiro.Permission;

/**
 * 通用控制器-JqGrid
 * 
 * @文件 :BaseJqGridController.java
 * @作者 :cn.loioi
 * @创建时间 :2016年10月13日 下午1:10:43
 */
public abstract class BaseDataTableController<T, S extends BaseService<T>> extends AbstractTableController<T, S> {

	public BaseDataTableController(String baseTemplateUrl, String identity, S baseService) {
		super(baseTemplateUrl, identity, baseService);
	}

	public BaseDataTableController(String baseTemplateUrl, S baseService) {
		super(baseTemplateUrl, baseService);
	}

	/**
	 * 获取数据接口
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping("list.json")
	public Model list(HttpServletRequest request, Model model) throws Exception {
		checkPermission(request, Permission.VIEW.parts(_identity));// 检查用户的权限是否可以访问

		DataTableRequest dataTableReq = new DataTableRequest(request);
		try {
			PageInfo<?> page = getData(request, dataTableReq);

			model.addAttribute("recordsFiltered", page.getTotal());
			model.addAttribute("recordsTotal", page.getTotal());
			model.addAttribute("data", page.getList());
		} catch (Exception e) {
			model.addAttribute("recordsFiltered", 0);
			model.addAttribute("recordsTotal", 0);
			model.addAttribute("data", new ArrayList<>());
			model.addAttribute("error", e.getMessage());
		}

		model.addAttribute("draw", dataTableReq.getDraw());
		return model;
	}

	@Override
	protected void savePageInfo(HttpServletRequest request, Model model) {
	}
}
